// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const ipc = require("electron").ipcRenderer;
const { shell, app } = require("electron");
var path = require("path");

var closeBtn = document.getElementById("close");

if (closeBtn) {
  closeBtn.addEventListener("click", () => {
    ipc.send("close-app");
  });
}

const screenDoShot = require("./Do");
const { listenerCount } = require("process");

document
  .getElementById("openLessonFolder")
  .addEventListener("click", function () {
    var exePath = process.execPath.replace("app.exe", "") + "book";
    console.log(exePath, "==========exePath===========");
    shell.openItem(exePath);
  });

document.getElementById("startDo").addEventListener("click", function () {
  var username = document.getElementById("username").value || "";
  var password = document.getElementById("password").value || "";

  if (username.length == 0 || password.length == 0) {
    alert("请先输入帐号或密码");
    return false;
  }

  if (this.getAttribute("disabled") == "disabled") {
    return;
  }

  this.setAttribute("disabled", "disabled");

  this.innerText = "爬取中,请耐心等待。如有问题,请关闭后重新打开试试";

  var url = document.getElementById("input-url").value.trim() || "";

  console.log(url);

  if (url.length == 0 && url.indexOf("http") != 0) {
    alert("请填入正常的url地址");
    return;
  }

  var headless = true;
  if (document.getElementById("headless_0").checked) {
    headless = false;
  }

  var network = 1;

  if (document.getElementById("network_2").checked) {
    network = parseFloat(document.getElementById("network_2").value);
  }

  if (document.getElementById("network_3").checked) {
    network = parseFloat(document.getElementById("network_3").value);
  }

  if (document.getElementById("network_test").checked) {
    network = parseFloat(document.getElementById("network_test").value);
  }

  console.log(network);

  screenDoShot(url, headless, network, {
    username:username,
    password:password
  },function (log) {
    var lodDom = document.getElementById("log_container");

    lodDom.scrollTop = lodDom.scrollHeight;

    if (log == "截取完成") {
      lodDom.value = lodDom.value + "[结束:" + log + "]\r\n";
      document.getElementById("startDo").removeAttribute("disabled");
      document.getElementById("startDo").innerText = "开始爬取";
      alert(log);
      return;
    }

    if (log.lastIndexOf("已存在以lesson名为") > -1) {
      lodDom.value = lodDom.value + "[结束:" + log + "]\r\n";
      alert(log);
      return;
    }

    lodDom.value = lodDom.value + log + "\r\n";
  });

  // window.location.href = '/do?page_url=' + url;
});
